package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisConst;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Setmeal;
import com.itheima.utils.QiniuUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.JedisPool;
import service.SetmealService;

import java.io.IOException;
import java.util.UUID;

/**
 * ClassName: SetmealController
 * Description:
 * date: 2019/11/21 21:19
 * Author Airson
 * Since JDK 1.8
 */
@RestController
@RequestMapping("/setmeal")
public class SetmealController {

    //注入业务层
    @Reference
    SetmealService setmealService;
    @Autowired
    JedisPool jedisPool;

    //图片上传方法
    @RequestMapping("/upload")
    public Result upload(MultipartFile imgFile) {

        try {
            System.out.println(imgFile);
            //生成唯一方法名
            String onlyId = UUID.randomUUID().toString().replace("-", "");
            //获得原文件名
            String originalFilename = imgFile.getOriginalFilename();
            //截取后缀名
            String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
            //生成新的唯一文件名上传服务器
            String serveName = onlyId + substring;
            //上传文件
            QiniuUtils.upload2Qiniu(imgFile.getBytes(), serveName);
            //保存图片名称到redis
            jedisPool.getResource().sadd(RedisConst.SETMEAL_PIC_RESOURCES,serveName);

            return new Result(true, MessageConstant.PIC_UPLOAD_SUCCESS, serveName);
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.PIC_UPLOAD_FAIL);
        }
    }

    /**
     * 添加表单信息
     *
     * @return
     */
    @RequestMapping("add")
    public Result add(Integer[] checkgroupIds, @RequestBody Setmeal setmeal) {

        try {
            setmealService.add(checkgroupIds, setmeal);
            return new Result(true, MessageConstant.ADD_SETMEAL_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.ADD_SETMEAL_FAIL);
        }
    }

    /**
     * 分页查询
     *
     * @param queryPageBean
     * @return
     */
    @RequestMapping("findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean) {
        return setmealService.findPage(queryPageBean);
    }
}
